package restaurant.dao.impl;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;

import restaurant.dao.FoodDao;
import restaurant.pojo.Foods;
import restaurant.pojo.FoodsType;
import restaurant.utils.BaseDao;

public class FoodDaoImpl extends BaseDao implements FoodDao{

	@Override
	public int addFood(Foods food) throws SQLException {
		String sql = "insert into foods values (null,?,?,?,?,?,?)";
		int i = qr.update(sql, food.getFoodname(),food.getId(),food.getPrice(),food.getVprice(),food.getInfo(),food.getImgurl());
		return i;
	}

	@Override
	public List<FoodsType> getAllType() throws SQLException {
		String sql = "select * from foodstype";
		List<FoodsType> type = qr.query(sql, new BeanListHandler<FoodsType>(FoodsType.class));
		return type;
	}

	@Override
	public List<Foods> showFood(int offset, int pagesize) throws SQLException {
		String sql = "select f.id, foodname, tid, info, t.type as type, imgurl, price,vprice from foods as f left outer join foodstype as t on f.tid = t.id order by tid limit ?,?";
		List<Foods> foods = qr.query(sql, new BeanListHandler<Foods>(Foods.class),offset,pagesize);
		return foods;
	}

	@Override
	public long getCount() throws SQLException {
		String sql = "select count(*) as count from foods";
		Map<String, Object> map = qr.query(sql, new MapHandler());
		return (long) map.get("count");
	}

	@Override
	public int deleFood(String id) throws SQLException {
		String sql = "delete from foods where id = ?";
		int i = qr.update(sql, id);
		return i;
	}

	@Override
	public int updateFood(Foods food) throws SQLException {
		String sql = "update foods set foodname=?,tid=?,price=?,vprice=?,info=?,imgurl=? where id = ?";
		int i = qr.update(sql, food.getFoodname(),food.getTid(),food.getPrice(),food.getVprice(),food.getInfo(),food.getImgurl(),food.getId());
		return i;
	}

	@Override
	public List<Foods> find(String param) throws SQLException {
		param = "%" + param + "%";
		String sql = "select f.id, foodname, tid, info, t.type as type, imgurl, price,vprice from foods as f left outer join foodstype as t on f.tid = t.id where foodname like ?";
		List<Foods> food = qr.query(sql, new BeanListHandler<Foods>(Foods.class), param);
		return food;
	}
	
}
